<template>
  <div class="page-container">
    <h1>Stock Price</h1>
    <div>
      <ul class="ulBg" id="chatContainer">
        <li v-for="(item, index) in list" :key="index">
          <span>{{item.timestamp}}</span>
          <span>{{item.threadName}}</span>
          <span>{{item.level}}</span>
          <span>{{item.className}}</span>
          <span>{{item.body}}</span>
          </li>
      </ul>
    </div>
    <button @click="senMessage">发送消息</button>
    <button @click="closeSocket">关闭</button>
  </div>
</template>
<script>
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
import Cookies from 'js-cookie'
export default {
  data() {
    return {
      list: [],
      stompClient: null
    }
  },
  created: {},
  mounted () {
    this.initWebSocket()
  },
  destroyed () {
    this.closeSocket()
  },
  // computed () {
  //   this.chatlog()
  // },
  updated () {
    this.scrollToBottom()
  },
  methods: {
    scrollToBottom () {
      this.$nextTick(() => {
        const container = this.$el.querySelector(" #chatContainer")
        container.scrollTop = container.scrollHeight
      })
    },
    senMessage () { // this.stompClient.send('/app/hello')
      this.initWebSocket()
    },
    // 初始化连接
    initWebSocket () {
      this.connection()
      // 需要有一个失败重连得到问题
    },
    connection () {
      // 更换that指针
      const url = window.SITE_CONFIG.baseUrl + '/sys/weblog' + '?token=' + Cookies.get('token')
      const socket = new SockJS(url)
      this.stompClient = Stomp.over(socket)
      this.connect()
      // 回调函数 3 end
    },
    onopen () {

    },
    // 建立连接
    connect () {
      const token = Cookies.get('token')
      const authorization = Cookies.get('authorization')
      const headers = { token: token, authorization: authorization }
      this.stompClient.connect(headers, (frame) => { // 建立连接，订阅主题
        this.stompClient.subscribe('/topic/log', (val) => {
          if (this.list.length > 100) {
            this.list.shift()
          }
          this.list.push(JSON.parse(val.body))
        })
      })
    },
    // 关闭连接
    closeSocket () {
      if (this.stompClient != null) {
        this.stompClient.disconnect()
        this.stompClient = null
      }
    }
  }
}
</script>
<style scoped>
  .ulBg{
    background: #333333;
    color: #fafafa;
    text-align: left;
    height: 500px;
    overflow: auto;
  }
  ul li {
    list-style-type:none
  }
  ul li span {
    margin-right: 10px;
    margin-top: 5px;
  }
</style>
